// ==UserScript==
// @name         成都住建优化脚本
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  优化成都住建网站的预售项目列表和一房一价展示
// @author       You
// @match        https://www.cdzjryb.com/SCXX/Default.aspx?action=ucSCXXShowNew2
// @match        https://zw.cdzjryb.com/roompricezjw/index.html*
// @grant        GM_addStyle
// @grant        GM_getResourceText
// @resource     DTCSS https://cdn.datatables.net/1.10.24/css/jquery.dataTables.min.css
// @require      https://code.jquery.com/jquery-3.6.0.min.js
// @require      https://cdn.datatables.net/1.10.24/js/jquery.dataTables.min.js
// ==/UserScript==

(function () {
    'use strict';

    // 日志函数
    const log = (...args) => {
        console.log('[成都住建优化]', ...args);
    };

    // 判断当前页面类型
    const isProjectList = window.location.href.includes('Default.aspx');
    const isRoomPrice = window.location.href.includes('roompricezjw');

    // 预售项目列表页面样式
    const projectListStyles = `
        /* 顶部导航区域样式 */
        .menu {
            background: linear-gradient(145deg, #f0f0f0, #e6e6e6) !important;
            height: auto !important;
            padding: 6px 0;
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            z-index: 1000;
            box-shadow: 0 5px 15px rgba(0,0,0,0.05);
            backdrop-filter: blur(10px);
            transition: all 0.3s ease;
        }

        /* 顶部导航滚动状态 */
        .menu.scrolled {
            padding: 5px 0;
            background: linear-gradient(145deg, #e8e8e8, #dedede) !important;
            backdrop-filter: blur(20px);
        }

        /* 菜单容器 */
        .menu-container {
            max-width: 1400px !important;
            margin: 0 auto !important;
            position: relative;
            display: flex !important;
            justify-content: flex-start;
            align-items: center;
            padding: 0 30px;
            height: 40px;
            width: 100%;
            box-sizing: border-box;
        }

        /* 左侧菜单区域 */
        .menu-left {
            display: flex;
            align-items: center;
            flex: 1;
            height: 100%;
        }

        /* Logo样式 */
        .menu-logo {
            font-size: 18px !important;
            font-weight: 600 !important;
            color: #308cde !important;
            text-shadow: 2px 2px 4px rgba(0,0,0,0.1);
            letter-spacing: 1px;
            margin-right: 15px;
            white-space: nowrap;
        }

        /* 菜单导航区域 */
        .menu-nav {
            display: flex;
            align-items: center;
            gap: 3px;
            flex: 1;
        }

        /* 菜单按钮样式 */
        .menuItem {
            color: #666 !important;
            font-size: 15px !important;
            text-decoration: none !important;
            padding: 6px 12px !important;
            border-radius: 8px !important;
            background: linear-gradient(145deg, #f5f5f5, #ffffff) !important;
            box-shadow: 2px 2px 4px #bebebe, -2px -2px 4px #ffffff !important;
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1) !important;
            position: relative !important;
            overflow: hidden !important;
            display: inline-flex !important;
            align-items: center !important;
            margin: 0 1px !important;
            border: none !important;
            height: 28px !important;
            line-height: 28px !important;
            white-space: nowrap !important;
            min-width: fit-content !important;
            width: auto !important;
        }

        .menuItem::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: linear-gradient(120deg, transparent, rgba(48,140,222,0.1), transparent);
            transform: translateX(-100%);
            transition: 0.6s;
        }

        .menuItem:hover {
            color: #308cde !important;
            transform: translateY(-2px);
            box-shadow: 3px 3px 6px #bebebe, -3px -3px 6px #ffffff !important;
        }

        .menuItem:hover::before {
            transform: translateX(100%);
        }

        .menuItem::after {
            content: '';
            position: absolute;
            bottom: 0;
            left: 50%;
            width: 0;
            height: 2px;
            background: #308cde;
            transition: all 0.3s ease;
            transform: translateX(-50%);
        }

        .menuItem:hover::after {
            width: 70%;
        }

        .menuItemSel {
            color: #308cde !important;
            font-weight: 600 !important;
            background: linear-gradient(145deg, #e8f3ff, #ffffff) !important;
            box-shadow: inset 3px 3px 6px #bebebe, inset -3px -3px 6px #ffffff !important;
        }

        .menuItemSel::after {
            content: '';
            position: absolute;
            bottom: 0;
            left: 50%;
            width: 70%;
            height: 2px;
            background: #308cde;
            transform: translateX(-50%);
        }

        /* 右侧搜索区域 */
        .menu-right {
            display: flex;
            align-items: center;
            gap: 5px;
            margin-left: auto !important;
            padding-left: 20px !important;
            flex-shrink: 0;
        }

        /* 搜索框样式 */
        #KeyWord {
            border: none;
            padding: 0 15px;
            height: 28px !important;
            line-height: 28px !important;
            border-radius: 20px;
            background: linear-gradient(145deg, #e6e6e6, #f0f0f0);
            box-shadow: inset 4px 4px 8px #bebebe, 
                        inset -4px -4px 8px #ffffff;
            width: 200px !important;
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
            font-size: 14px;
            color: #666;
        }

        #KeyWord:focus {
            outline: none;
            box-shadow: inset 6px 6px 12px #bebebe, 
                        inset -6px -6px 12px #ffffff;
        }

        #KeyWord::placeholder {
            color: #888;
            font-size: 12px;
            font-style: italic;
        }

        /* 搜索按钮样式 */
        .topSearchTitle {
            border: none !important;
            padding: 0 15px !important;
            height: 28px !important;
            line-height: 28px !important;
            border-radius: 20px !important;
            background: linear-gradient(145deg, #3498db, #2980b9) !important;
            color: white !important;
            cursor: pointer !important;
            box-shadow: 5px 5px 10px #bebebe, 
                        -5px -5px 10px #ffffff !important;
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1) !important;
            font-size: 15px !important;
            height: auto !important;
            margin: 0 !important;
            position: relative;
            overflow: hidden;
            min-width: 60px;
            font-weight: 500 !important;
            letter-spacing: 1px;
            display: inline-flex !important;
            align-items: center !important;
            justify-content: center !important;
        }

        .topSearchTitle:hover {
            transform: translateY(-1px);
            background: linear-gradient(145deg, #2980b9, #3498db) !important;
            box-shadow: 6px 6px 12px #bebebe, 
                        -6px -6px 12px #ffffff !important;
        }

        .topSearchTitle:active {
            transform: translateY(0);
            box-shadow: inset 4px 4px 8px #1e5584,
                        inset -4px -4px 8px #308cde !important;
        }

        .topSearchTitle::after {
            content: '';
            position: absolute;
            top: 50%;
            left: 50%;
            width: 0;
            height: 0;
            background: rgba(255,255,255,0.2);
            border-radius: 50%;
            transform: translate(-50%, -50%);
            transition: width 0.6s ease-out, height 0.6s ease-out;
        }

        .topSearchTitle:hover::after {
            width: 150%;
            height: 150%;
        }

        /* 调整主内容区域位置 */
        .rightContent {
            margin-top: 45px !important;
            background: #e0e0e0;
            padding: 20px;
            border-radius: 20px;
            box-shadow: 20px 20px 60px #bebebe, -20px -20px 60px #ffffff;
            width: 95% !important;
            margin-left: auto !important;
            margin-right: auto !important;
        }

        /* 调整内容区域宽度 */
        #form1 > div:nth-child(4) > div:nth-child(8) {
            width: 100% !important;
            margin: 0 !important;
            padding: 0 !important;
        }

        /* 调整表格容器宽度 */
        #form1 > div:nth-child(4) > div:nth-child(8) > div {
            width: 100% !important;
        }

        /* 调整内容区域上边距 */
        #form1 > div:nth-child(4) > div:nth-child(8) > div > div > div > div {
            margin-top: 10px !important;
        }

        /* 调整表格容器上边距 */
        #form1 > div:nth-child(4) > div:nth-child(8) > div > div > div > div > div:nth-child(2) {
            margin-top: 0 !important;
        }

        /* 标题样式 */
        .listTitle {
            padding: 15px;
            border-radius: 10px;
            background: linear-gradient(145deg, #e6e6e6, #ffffff);
            box-shadow: 5px 5px 10px #bebebe, -5px -5px 10px #ffffff;
            margin-bottom: 10px;
        }

        .listTitle span {
            color: #308cde;
            font-size: 18px;
            font-weight: bold;
        }

        /* 隐藏分割线 */
        .listLine > div {
            display: none;
        }

        /* 输入框样式 */
        input[type="text"] {
            border: none;
            padding: 8px 15px;
            border-radius: 8px;
            background: #e0e0e0;
            box-shadow: inset 3px 3px 6px #bebebe, inset -3px -3px 6px #ffffff;
            transition: all 0.3s ease;
        }

        /* 按钮样式 */
        .right_new_btn {
            border: none;
            padding: 8px 20px;
            border-radius: 8px;
            background: linear-gradient(145deg, #308cde, #2674bc);
            color: white;
            cursor: pointer;
            box-shadow: 3px 3px 6px #bebebe, -3px -3px 6px #ffffff;
            transition: all 0.3s ease;
        }

        .right_new_btn:hover {
            background: linear-gradient(145deg, #2674bc, #308cde);
            transform: translateY(-2px);
        }

        .right_new_btn:active {
            transform: translateY(0);
            box-shadow: inset 3px 3px 6px #1e5584, inset -3px -3px 6px #308cde;
        }

        /* 表格样式优化 */
        #ID_ucSCXXShowNew2_gridView {
            border-collapse: collapse;
            width: 100%;
            margin: 5px 0;
            background: #e0e0e0;
            border-radius: 8px;
            overflow: hidden;
            box-shadow: 5px 5px 10px #bebebe, -5px -5px 10px #ffffff;
            table-layout: auto;
        }

        /* 预售面积列宽度控 */
        #ID_ucSCXXShowNew2_gridView th:nth-child(7),
        #ID_ucSCXXShowNew2_gridView td:nth-child(7) {
            width: 100px;
            max-width: 100px;
            text-align: right;
            padding-right: 15px;
        }

        /* 数字添加千分位分隔符 */
        #ID_ucSCXXShowNew2_gridView td:nth-child(7) {
            font-family: Monaco, Consolas, monospace;
        }

        /* 预/现售号按钮样式 */
        .PIDLink {
            border: none !important;
            background-color: transparent !important;
            color: #308cde !important;
            text-decoration: underline !important;
            cursor: pointer !important;
            padding: 0 !important;
            transition: all 0.3s ease !important;
        }

        .PIDLink:hover {
            color: #2674bc !important;
            text-decoration: none !important;
        }

        #ID_ucSCXXShowNew2_gridView th {
            background: linear-gradient(145deg, #308cde, #2674bc);
            color: white;
            padding: 12px 8px;
            font-weight: 500;
            white-space: nowrap;
        }

        #ID_ucSCXXShowNew2_gridView td {
            padding: 10px 8px;
            border: none;
            background: #e0e0e0;
            transition: all 0.3s ease;
            white-space: normal;
            word-break: break-word;
        }

        #ID_ucSCXXShowNew2_gridView tr:hover {
            background: linear-gradient(145deg, #e6e6e6, #ffffff);
            box-shadow: inset 3px 3px 6px #bebebe, inset -3px -3px 6px #ffffff;
        }

        /* 分页区域样式 */
        .meneame {
            padding: 15px;
            border-radius: 10px;
            background: #e0e0e0;
            box-shadow: inset 3px 3px 6px #bebebe, inset -3px -3px 6px #ffffff;
            margin-top: 20px;
        }

        .meneame a {
            padding: 5px 10px;
            margin: 0 3px;
            border-radius: 5px;
            background: linear-gradient(145deg, #e6e6e6, #ffffff);
            box-shadow: 3px 3px 6px #bebebe, -3px -3px 6px #ffffff;
            color: #308cde;
            text-decoration: none;
            transition: all 0.3s ease;
        }

        .meneame a:hover {
            background: linear-gradient(145deg, #308cde, #2674bc);
            color: white;
        }

        .meneame .current {
            padding: 5px 10px;
            margin: 0 3px;
            border-radius: 5px;
            background: linear-gradient(145deg, #308cde, #2674bc);
            color: white;
            box-shadow: inset 3px 3px 6px #1e5584, inset -3px -3px 6px #308cde;
        }

        /* 一房一价弹窗样式 */
        .price-modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,0.5);
            z-index: 9999;
            overflow: hidden;
        }

        .price-modal-content {
            position: relative;
            width: 95%;
            height: 95%;
            margin: 20px auto;
            background: #e0e0e0;
            border-radius: 8px;
            padding: 20px;
            box-shadow: 20px 20px 60px #bebebe, -20px -20px 60px #ffffff;
            overflow: hidden;
            display: flex;
            flex-direction: column;
        }

        .price-modal-close {
            position: absolute;
            right: 20px;
            top: 10px;
            font-size: 24px;
            color: #666;
            cursor: pointer;
            z-index: 10000;
        }

        .price-modal-close:hover {
            color: #333;
        }

        .price-modal iframe {
            width: 100%;
            flex: 1;
            border: none;
            overflow: auto;
        }

        /* 禁止滚动的样式 */
        .body-no-scroll {
            overflow: hidden !important;
            padding-right: 17px; /* 防止滚动条消失导致页面抖动 */
        }

        .favorite-btn {
            cursor: pointer;
            color: #999;
            margin-right: 5px;
            transition: color 0.3s;
        }
        .favorite-btn.active {
            color: #f0a500;
        }
        .favorites-container {
            position: fixed;
            right: -350px;
            top: 50%;
            transform: translateY(-50%);
            width: 350px;
            background: #fff;
            box-shadow: -2px 0 8px rgba(0,0,0,0.1);
            transition: right 0.3s;
            z-index: 9999;
            border-radius: 8px 0 0 8px;
            padding: 15px;
        }
        .favorites-container.show {
            right: 0;
        }
        .favorites-toggle {
            position: absolute;
            left: -40px;
            top: 50%;
            transform: translateY(-50%);
            background: #308cde;
            color: #fff;
            padding: 10px;
            cursor: pointer;
            writing-mode: vertical-rl;
            border-radius: 4px 0 0 4px;
        }
        .favorites-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 15px;
            padding-bottom: 10px;
            border-bottom: 1px solid #eee;
        }
        .favorites-title {
            font-size: 16px;
            font-weight: bold;
        }
        .favorites-clear {
            color: #ff4d4f;
            cursor: pointer;
            font-size: 14px;
        }
        .favorites-list {
            max-height: 600px;
            overflow-y: auto;
        }
        .favorite-item {
            padding: 10px;
            border-bottom: 1px solid #eee;
            font-size: 14px;
        }
        .favorite-item:hover {
            background: #f5f5f5;
        }
        .favorite-item-title {
            font-weight: bold;
            margin-bottom: 5px;
        }
        .favorite-item-info {
            color: #666;
            margin-bottom: 5px;
        }
        .favorite-item-actions {
            display: flex;
            gap: 10px;
        }
        .favorite-item-actions a {
            color: #308cde;
            text-decoration: none;
        }
        .favorite-item-actions a:hover {
            text-decoration: underline;
        }

        /* 收藏项目卡片样式优化 */
        .favorite-item {
            padding: 15px;
            margin: 10px 0;
            border-radius: 12px;
            background: linear-gradient(145deg, #f0f0f0, #ffffff);
            box-shadow: 5px 5px 10px #bebebe, -5px -5px 10px #ffffff;
            transition: all 0.3s ease;
            border: none;
        }

        .favorite-item:hover {
            transform: translateY(-2px);
            box-shadow: 8px 8px 16px #bebebe, -8px -8px 16px #ffffff;
        }

        .favorite-item-title {
            font-size: 16px;
            font-weight: bold;
            color: #308cde;
            margin-bottom: 10px;
            padding-bottom: 8px;
            border-bottom: 2px solid #e8f3ff;
        }

        .favorite-item-info {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 8px;
            margin-bottom: 12px;
            font-size: 13px;
        }

        .favorite-item-info-row {
            display: flex;
            align-items: center;
            color: #666;
        }

        .favorite-item-info-label {
            color: #999;
            margin-right: 5px;
            flex-shrink: 0;
        }

        .favorite-item-info-value {
            color: #333;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
        }

        .favorite-item-actions {
            display: flex;
            gap: 10px;
            padding-top: 10px;
            border-top: 1px solid #eee;
        }

        .favorite-item-actions a {
            flex: 1;
            padding: 6px 12px;
            border-radius: 6px;
            text-align: center;
            text-decoration: none;
            font-size: 13px;
            transition: all 0.3s ease;
        }

        .favorite-item-actions .price-link {
            background: linear-gradient(145deg, #308cde, #2674bc);
            color: white;
        }

        .favorite-item-actions .plan-link {
            background: linear-gradient(145deg, #f0f0f0, #ffffff);
            color: #308cde;
            border: 1px solid #308cde;
        }

        .favorite-item-actions a:hover {
            transform: translateY(-1px);
            filter: brightness(1.1);
            text-decoration: none;
        }

        .favorite-item-actions a:active {
            transform: translateY(0);
            filter: brightness(0.9);
        }

        /* 收藏夹滚动条美化 */
        .favorites-list::-webkit-scrollbar {
            width: 8px;
        }

        .favorites-list::-webkit-scrollbar-track {
            background: #f1f1f1;
            border-radius: 4px;
        }

        .favorites-list::-webkit-scrollbar-thumb {
            background: #308cde;
            border-radius: 4px;
        }

        .favorites-list::-webkit-scrollbar-thumb:hover {
            background: #2674bc;
        }
    `;

    // 一房一价页面样式
    const roomPriceStyles = `
        .neo-table-container {
            border-radius: 20px;
            background: #e0e0e0;
            box-shadow: 20px 20px 60px #bebebe, -20px -20px 60px #ffffff;
            padding: 20px;
            margin: 20px;
        }
        
        .dataTables_wrapper {
            padding: 20px;
            background: #e0e0e0;
            border-radius: 15px;
        }
        
        .stats-container {
            margin-top: 20px;
            padding: 20px;
            border-radius: 10px;
            background: #e0e0e0;
            box-shadow: inset 5px 5px 10px #bebebe, inset -5px -5px 10px #ffffff;
        }
        
        .stats-container h3 {
            margin: 0 0 20px 0;
            color: #1e88e5;
            font-size: 18px;
            text-align: center;
            text-shadow: 1px 1px 2px #ffffff;
        }
        
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 15px;
            padding: 10px;
        }
        
        .stats-item {
            padding: 15px;
            border-radius: 12px;
            background: linear-gradient(145deg, #e6e6e6, #ffffff);
            box-shadow: 5px 5px 10px #bebebe, -5px -5px 10px #ffffff;
            transition: transform 0.3s ease;
        }
        
        .stats-item:hover {
            transform: translateY(-2px);
        }
        
        .stats-item-label {
            font-size: 14px;
            color: #666;
            margin-bottom: 8px;
        }
        
        .stats-item-value {
            font-size: 18px;
            font-weight: bold;
            color: #1e88e5;
        }
        
        .stats-item.highlight {
            background: linear-gradient(145deg, #e3f2fd, #bbdefb);
        }
        
        .stats-item.warning {
            background: linear-gradient(145deg, #fff3e0, #ffe0b2);
        }
        
        .stats-item.success {
            background: linear-gradient(145deg, #e8f5e9, #c8e6c9);
        }

        .price-modal-close {
            position: absolute;
            right: 20px;
            top: 10px;
            font-size: 24px;
            color: #666;
            cursor: pointer;
            z-index: 10000;
            transition: all 0.3s ease;
            width: 32px;
            height: 32px;
            line-height: 32px;
            text-align: center;
            border-radius: 50%;
        }

        .price-modal-close:hover {
            color: #333;
            background: rgba(0,0,0,0.05);
            transform: rotate(180deg);
        }
    `;

    // 等待元素出现的函数
    function waitForElement(selector, timeout = 10000) {
        return new Promise((resolve, reject) => {
            const startTime = Date.now();
            const checkElement = () => {
                const element = document.querySelector(selector);
                if (element) {
                    resolve(element);
                    return;
                }
                if (Date.now() - startTime > timeout) {
                    reject(new Error(`等待元素 ${selector} 超时`));
                    return;
                }
                setTimeout(checkElement, 100);
            };
            checkElement();
        });
    }

    // 预售项目列表页面优化
    function enhanceProjectList() {
        log('开始优化预售项目列表');

        // 添加样式
        GM_addStyle(projectListStyles);

        // 重构菜单结构
        const menu = document.querySelector('.menu');
        if (menu) {
            // 移除原有背景图
            menu.style.backgroundImage = 'none';

            // 获取原始内容
            const originalTable = menu.querySelector('table');
            const logo = originalTable.querySelector('td:first-child span').textContent;
            const menuItems = Array.from(originalTable.querySelectorAll('.menuItem'));
            const searchContainer = originalTable.querySelector('td:last-child > div');

            // 创建新的菜单结构
            const menuContainer = document.createElement('div');
            menuContainer.className = 'menu-container';

            // 创建左侧区域
            const menuLeft = document.createElement('div');
            menuLeft.className = 'menu-left';

            // 添加Logo
            const menuLogo = document.createElement('div');
            menuLogo.className = 'menu-logo';
            menuLogo.textContent = logo;
            menuLeft.appendChild(menuLogo);

            // 添加导航菜单
            const menuNav = document.createElement('div');
            menuNav.className = 'menu-nav';
            menuItems.forEach(item => {
                const newItem = item.cloneNode(true);
                menuNav.appendChild(newItem);
            });
            menuLeft.appendChild(menuNav);

            // 创建右侧搜索区域
            const menuRight = document.createElement('div');
            menuRight.className = 'menu-right';
            menuRight.appendChild(searchContainer.cloneNode(true));

            // 组装菜单
            menuContainer.appendChild(menuLeft);
            menuContainer.appendChild(menuRight);

            // 替换原始菜单内容
            menu.innerHTML = '';
            menu.appendChild(menuContainer);

            // 标记当前选中的菜单项
            const currentPath = window.location.pathname;
            const newMenuItems = menu.querySelectorAll('.menuItem');
            newMenuItems.forEach(item => {
                if (item.href && item.href.includes(currentPath)) {
                    item.classList.add('menuItemSel');
                }
            });
        }

        // 创建弹窗容器
        const modal = document.createElement('div');
        modal.className = 'price-modal';
        modal.innerHTML = `
            <div class="price-modal-content">
                <span class="price-modal-close">×</span>
                <iframe></iframe>
            </div>
        `;
        document.body.appendChild(modal);

        // 处理一房一价链接点击
        const priceLinks = document.querySelectorAll('a[id*="hyPresLink"]');
        priceLinks.forEach(link => {
            link.addEventListener('click', (e) => {
                e.preventDefault();
                const url = link.href;
                modal.querySelector('iframe').src = url;
                modal.style.display = 'block';
                document.body.classList.add('body-no-scroll');
            });
        });

        // 关闭弹窗
        modal.querySelector('.price-modal-close').addEventListener('click', () => {
            modal.style.display = 'none';
            modal.querySelector('iframe').src = '';
            document.body.classList.remove('body-no-scroll');
        });

        // 点击弹窗外区域关闭
        modal.addEventListener('click', (e) => {
            if (e.target === modal) {
                modal.style.display = 'none';
                modal.querySelector('iframe').src = '';
                document.body.classList.remove('body-no-scroll');
            }
        });

        // 阻止弹窗内容区域的点击事件冒泡
        modal.querySelector('.price-modal-content').addEventListener('click', (e) => {
            e.stopPropagation();
        });

        // 监听 ESC 键关闭弹窗
        document.addEventListener('keydown', (e) => {
            if (e.key === 'Escape' && modal.style.display === 'block') {
                modal.style.display = 'none';
                modal.querySelector('iframe').src = '';
                document.body.classList.remove('body-no-scroll');
            }
        });

        // 添加滚动监听
        window.addEventListener('scroll', () => {
            const menu = document.querySelector('.menu');
            if (window.scrollY > 10) {
                menu.classList.add('scrolled');
            } else {
                menu.classList.remove('scrolled');
            }
        });

        // 修改搜索框占位符
        const searchInput = document.getElementById('KeyWord');
        if (searchInput) {
            searchInput.placeholder = '搜索项名称、区域...';
        }

        // 创建收藏夹容器
        const favoritesContainer = document.createElement('div');
        favoritesContainer.className = 'favorites-container';
        favoritesContainer.innerHTML = `
            <div class="favorites-toggle">收藏夹</div>
            <div class="favorites-header">
                <div class="favorites-title">收藏的项目</div>
                <div class="favorites-clear">清空</div>
            </div>
            <div class="favorites-list"></div>
        `;
        document.body.appendChild(favoritesContainer);

        // 切换收藏夹显示
        favoritesContainer.querySelector('.favorites-toggle').addEventListener('click', () => {
            favoritesContainer.classList.toggle('show');
            if (favoritesContainer.classList.contains('show')) {
                updateFavoritesList();
            }
        });

        // 清空收藏
        favoritesContainer.querySelector('.favorites-clear').addEventListener('click', () => {
            if (confirm('确定要清空所有收藏的项目吗？')) {
                localStorage.removeItem('favoriteProjects');
                updateFavoritesList();
                updateFavoriteButtons();
            }
        });

        // 切换收藏状态
        function toggleFavorite(e) {
            const btn = e.target;
            const projectData = JSON.parse(btn.dataset.project);
            const favorites = JSON.parse(localStorage.getItem('favoriteProjects') || '{}');

            if (favorites[projectData.id]) {
                delete favorites[projectData.id];
                btn.classList.remove('active');
            } else {
                favorites[projectData.id] = projectData;
                btn.classList.add('active');
            }

            localStorage.setItem('favoriteProjects', JSON.stringify(favorites));
            updateFavoritesList();
        }

        // 更新收藏列表显示
        function updateFavoritesList() {
            const favorites = JSON.parse(localStorage.getItem('favoriteProjects') || '{}');
            const listContainer = favoritesContainer.querySelector('.favorites-list');
            listContainer.innerHTML = '';

            Object.values(favorites).forEach(project => {
                const item = document.createElement('div');
                item.className = 'favorite-item';
                item.innerHTML = `
                    <div class="favorite-item-title">${project.name}</div>
                    <div class="favorite-item-info">
                        <div class="favorite-item-info-row">
                            <span class="favorite-item-info-label">区域：</span>
                            <span class="favorite-item-info-value">${project.area}</span>
                        </div>
                        <div class="favorite-item-info-row">
                            <span class="favorite-item-info-label">用途：</span>
                            <span class="favorite-item-info-value">${project.usage}</span>
                        </div>
                        <div class="favorite-item-info-row" style="grid-column: 1 / -1">
                            <span class="favorite-item-info-label">地址：</span>
                            <span class="favorite-item-info-value">${project.address}</span>
                        </div>
                        <div class="favorite-item-info-row" style="grid-column: 1 / -1">
                            <span class="favorite-item-info-label">开发商：</span>
                            <span class="favorite-item-info-value">${project.developer}</span>
                        </div>
                    </div>
                    <div class="favorite-item-actions">
                        ${project.priceLink ? `<a href="${project.priceLink}" class="price-link">查看一房一价</a>` : ''}
                        ${project.planLink ? `<a href="${project.planLink}" class="plan-link" target="_blank">查看预售方案</a>` : ''}
                    </div>
                `;
                listContainer.appendChild(item);
            });

            // 处理收藏列表中的一房一价链接
            const priceLinks = listContainer.querySelectorAll('.price-link');
            priceLinks.forEach(link => {
                link.addEventListener('click', (e) => {
                    e.preventDefault();
                    const url = link.href;
                    modal.querySelector('iframe').src = url;
                    modal.style.display = 'block';
                    document.body.classList.add('body-no-scroll');
                });
            });
        }

        // 更新所有收藏按钮状态
        function updateFavoriteButtons() {
            const favorites = JSON.parse(localStorage.getItem('favoriteProjects') || '{}');
            const buttons = document.querySelectorAll('.favorite-btn');
            buttons.forEach(btn => {
                const projectData = JSON.parse(btn.dataset.project);
                btn.classList.toggle('active', !!favorites[projectData.id]);
            });
        }

        // 优化表格内容显示和添加收藏功能
        const projectTable = document.getElementById('ID_ucSCXXShowNew2_gridView');
        if (projectTable) {
            // 处理长文本显示
            const cells = projectTable.querySelectorAll('td');
            cells.forEach(cell => {
                cell.title = cell.textContent;
                // 处理预售面积列的数字格式化
                if (cell.cellIndex === 6) { // 第7列是预售面积
                    const num = parseFloat(cell.textContent);
                    if (!isNaN(num)) {
                        cell.textContent = num.toLocaleString('zh-CN', {
                            minimumFractionDigits: 2,
                            maximumFractionDigits: 2
                        });
                    }
                }
            });

            // 添加收藏列到表头
            const headerRow = projectTable.querySelector('tr.boxHeader');
            const favoriteHeader = document.createElement('th');
            favoriteHeader.scope = 'col';
            favoriteHeader.textContent = '收藏';
            headerRow.insertBefore(favoriteHeader, headerRow.firstChild);

            // 为每行添加收藏按钮
            const rows = projectTable.querySelectorAll('tr:not(.boxHeader)');
            rows.forEach(row => {
                const favoriteCell = document.createElement('td');
                favoriteCell.className = 'boxItem';
                favoriteCell.style.width = '40px';
                favoriteCell.style.textAlign = 'center';

                const projectData = {
                    id: row.querySelector('input[type="submit"]')?.value || '',
                    name: row.cells[1]?.textContent.trim() || '',
                    area: row.cells[2]?.textContent.trim() || '',
                    address: row.cells[3]?.textContent.trim() || '',
                    usage: row.cells[4]?.textContent.trim() || '',
                    developer: row.cells[5]?.textContent.trim() || '',
                    priceLink: row.querySelector('a[id*="hyPresLink"]')?.href || '',
                    planLink: row.querySelector('a[id*="hySCXXViewLink"]')?.href || ''
                };

                if (projectData.id) {
                    const favoriteBtn = document.createElement('span');
                    favoriteBtn.className = 'favorite-btn';
                    favoriteBtn.innerHTML = '★';
                    favoriteBtn.dataset.project = JSON.stringify(projectData);

                    // 检查是否已收藏
                    const favorites = JSON.parse(localStorage.getItem('favoriteProjects') || '{}');
                    if (favorites[projectData.id]) {
                        favoriteBtn.classList.add('active');
                    }

                    favoriteBtn.addEventListener('click', toggleFavorite);
                    favoriteCell.appendChild(favoriteBtn);
                }

                row.insertBefore(favoriteCell, row.firstChild);
            });
        }
    }

    // 一房一价页面优化
    async function enhanceRoomPrice() {
        try {
            log('开始优化一房一价页面');

            // 添加 DataTables CSS
            try {
                const dtCSS = GM_getResourceText('DTCSS');
                GM_addStyle(dtCSS);
            } catch (error) {
                log('加载 DataTables CSS 失败:', error);
            }

            // 添加自定义样式
            GM_addStyle(roomPriceStyles);

            // 等待原始表格加载
            const originalTable = await waitForElement('.table-theme-gray.tbl-room:not(.tbl-fix) table');
            log('找到原始表格');

            // 提取表格数据
            const headers = Array.from(originalTable.querySelectorAll('thead th')).map(th => th.textContent.trim());
            const rows = Array.from(originalTable.querySelectorAll('tbody tr')).map(tr =>
                Array.from(tr.querySelectorAll('td')).map(td => {
                    const icon = td.querySelector('.icon');
                    if (icon) {
                        return icon.textContent.trim();
                    }
                    return td.textContent.trim();
                })
            );

            // 创建新容器和表格
            const container = document.createElement('div');
            container.className = 'neo-table-container';

            // 添加统计区域
            const statsContainer = document.createElement('div');
            statsContainer.className = 'stats-container';
            container.appendChild(statsContainer);

            // 创建表格容器
            const tableContainer = document.createElement('div');
            tableContainer.className = 'table-container';
            tableContainer.style.marginTop = '20px';

            // 创建新表格HTML
            let tableHtml = '<table id="enhanced-table" class="display"><thead><tr>';
            headers.forEach(header => {
                tableHtml += `<th>${header}</th>`;
            });
            tableHtml += '</tr></thead><tbody>';
            rows.forEach(row => {
                tableHtml += '<tr>';
                row.forEach(cell => {
                    tableHtml += `<td>${cell}</td>`;
                });
                tableHtml += '</tr>';
            });
            tableHtml += '</tbody></table>';

            tableContainer.innerHTML = tableHtml;
            container.appendChild(tableContainer);

            // 隐藏原表格并插入新表格
            const originalTableContainer = originalTable.closest('.table-view-wrap');
            originalTableContainer.style.display = 'none';
            originalTableContainer.parentNode.insertBefore(container, originalTableContainer);

            // 初始化 DataTable
            const dataTable = $('#enhanced-table').DataTable({
                language: {
                    url: 'https://cdn.datatables.net/plug-ins/1.10.24/i18n/Chinese.json'
                },
                pageLength: 10,
                lengthMenu: [[10, 25, 50, 100, -1], ['10条', '25条', '50条', '100条', '全部']],
                dom: '<"top"lf>rt<"bottom"ip>',
                initComplete: function () {
                    updateStats();
                }
            });

            // 更新统计信息
            function updateStats() {
                try {
                    const areaColumn = 3;
                    const priceColumn = 5;
                    const decorationColumn = 6;

                    const validRows = rows.filter(row => !row[priceColumn].includes('*'));
                    const areas = validRows.map(row => parseFloat(row[areaColumn]));
                    const prices = validRows.map(row => parseFloat(row[priceColumn].replace(/[^\d.]/g, '')));
                    const decorationPrices = validRows.map(row => parseFloat(row[decorationColumn].replace(/[^\d.]/g, '')));

                    const totalArea = areas.reduce((a, b) => a + b, 0);
                    const avgPrice = prices.length ? prices.reduce((a, b) => a + b, 0) / prices.length : 0;
                    const avgPricePerSqm = prices.length ? prices.reduce((a, b, i) => a + b / areas[i], 0) / prices.length : 0;
                    const maxPrice = prices.length ? Math.max(...prices) : 0;
                    const minPrice = prices.length ? Math.min(...prices) : 0;

                    statsContainer.innerHTML = `
                        <h3>房源统计分析</h3>
                        <div class="stats-grid">
                            <div class="stats-item highlight">
                                <div class="stats-item-label">总房源数量</div>
                                <div class="stats-item-value">${rows.length} 套</div>
                            </div>
                            <div class="stats-item success">
                                <div class="stats-item-label">可售房源</div>
                                <div class="stats-item-value">${rows.filter(row => row[8].includes('可售')).length} 套</div>
                            </div>
                            <div class="stats-item warning">
                                <div class="stats-item-label">已售房源</div>
                                <div class="stats-item-value">${rows.filter(row => row[8].includes('已售')).length} 套</div>
                            </div>
                            <div class="stats-item">
                                <div class="stats-item-label">总建筑面积</div>
                                <div class="stats-item-value">${totalArea.toFixed(2)} ㎡</div>
                            </div>
                            <div class="stats-item highlight">
                                <div class="stats-item-label">平均总价</div>
                                <div class="stats-item-value">${(avgPrice / 10000).toFixed(2)} 万元</div>
                            </div>
                            <div class="stats-item highlight">
                                <div class="stats-item-label">平均单价</div>
                                <div class="stats-item-value">${avgPricePerSqm.toFixed(2)} 元/㎡</div>
                            </div>
                            <div class="stats-item">
                                <div class="stats-item-label">最高总价</div>
                                <div class="stats-item-value">${(maxPrice / 10000).toFixed(2)} 万元</div>
                            </div>
                            <div class="stats-item">
                                <div class="stats-item-label">最低总价</div>
                                <div class="stats-item-value">${(minPrice / 10000).toFixed(2)} 万元</div>
                            </div>
                        </div>
                    `;
                } catch (error) {
                    log('统计计算出错:', error);
                }
            }

        } catch (error) {
            log('一房一价页面优化失败:', error);
            console.error(error);
        }
    }

    // 根据页面类型执行相应的优化
    if (isProjectList) {
        enhanceProjectList();
    } else if (isRoomPrice) {
        if (document.readyState === 'loading') {
            document.addEventListener('DOMContentLoaded', () => setTimeout(enhanceRoomPrice, 1000));
        } else {
            setTimeout(enhanceRoomPrice, 1000);
        }
    }

})();
